package esiag.pds.receivers;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import esiag.pds.beans.HostProvider;
import esiag.pds.contextManagement.Context;
import esiag.pds.interfaces.IContextProvider;
import esiag.pds.interfaces.IHostProvider;
import esiag.pds.interfaces.IgetContext;

public class ReplicationReceiver extends Thread{

	 	public static Logger log = Logger.getLogger("log_file");
	 	FileHandler hand;
	
   		 IgetContext rmiServer;
		 IContextProvider contextProvider;
		 IHostProvider hostprovider;
		
		 Registry registry;
		 int port;
		 boolean go=true;
	     Context context;	 
	
	public ReplicationReceiver(int port) {
		// TODO Auto-generated constructor stub
		context=new Context();
		hostprovider=new HostProvider();
		this.port=port;
		
		//Logger
		try {
			hand = new FileHandler("MonLog.txt");
			log.addHandler(hand);
			SimpleFormatter formatter=new SimpleFormatter();
			hand.setFormatter(formatter);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public int start(int frequency) {	
		try{
		while(go){
				  context=rmiWork();
				  context.getNbList();
				  log.info(">> A new version of context has just been received : <<\n"+
						  "Context FastLists count : "+ context.getNbList());
				  if(contextProvider!=null)
					  contextProvider.setContext(context.getTab());
				  Thread.sleep(frequency);
				}
		}catch(Exception e){
			try {   
					System.out.println("Server unreachable ");
					sleep(2000);
					return context.getNbList();
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				//	return getContext().getNbList();
				}
		}
		return context.getNbList();
	}

	public Context rmiWork(){
		
		log.info("\nReceiving Context from " +hostprovider.getHost()+ ":" + port 
				+ " at "+new Date());
		  try{
			  registry=LocateRegistry.getRegistry(hostprovider.getHost(),port);
			  rmiServer=(IgetContext)registry.lookup("Context");
			  // call the remote method
			  return rmiServer.getContext();			
		  }  catch(Exception e){
			  go=false;
			  System.out.println("Last version of context : NbListes"+getContext().getNbList());
			  return null;
		  }
	}
	
	public Context getContext(){
		return context;
	}
}
